﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.Administration;

namespace Macaw.Moss2007.CustomErrorPageSolution
{
    public class ManageCustomErrorPage : Microsoft.SharePoint.WebControls.LayoutsPageBase
    {

        protected RadioButtonList rblOptions;
        protected TextBox tbErrorPageUrl;

        protected override void OnLoad(EventArgs e)
        {
            if (!IsPostBack && SPContext.Current != null && SPContext.Current.Site != null)
            {
                ShowData();
            }

            base.OnLoad(e);
        }

        public void ShowData()
        {
            string customerrorpageurl = CustomErrorPageHelper.GetCustomErrorPageUrl(SPContext.Current.Site.ID , SPContext.Current.Web.ID, false);
            if (customerrorpageurl == null)
            {
                tbErrorPageUrl.Visible = false;
                rblOptions.SelectedIndex = rblOptions.Items.IndexOf( rblOptions.Items.FindByValue("Inherit") );
            }
            else if (customerrorpageurl == string.Empty)
            {
                tbErrorPageUrl.Visible = false;
                rblOptions.SelectedIndex = rblOptions.Items.IndexOf(rblOptions.Items.FindByValue("Disabled"));
            }
            else
            {
                tbErrorPageUrl.Visible = true;
                rblOptions.SelectedIndex = rblOptions.Items.IndexOf(rblOptions.Items.FindByValue("Enabled"));
                tbErrorPageUrl.Text = customerrorpageurl;
            }
        }

        protected void rblOptions_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            if (rblOptions.SelectedValue == "Enabled")
            {
                tbErrorPageUrl.Visible = true;
            }
            else
            {
                tbErrorPageUrl.Visible = false;
            }
        }

        public void btnSave_Click(object sender, EventArgs e)
        {
            if (rblOptions.SelectedValue!=null)
            {
                switch (rblOptions.SelectedValue)
                {
                    case "Inherit":
                        CustomErrorPageHelper.SetCustomErrorPageUrl(SPContext.Current.Web, null);
                        break;
                    case "Enabled":
                        CustomErrorPageHelper.SetCustomErrorPageUrl(SPContext.Current.Web, tbErrorPageUrl.Text);
                        break;
                    case "Disabled":
                        CustomErrorPageHelper.SetCustomErrorPageUrl(SPContext.Current.Web, string.Empty);
                        break;
                }
            
            }

            ShowData();
        }
    }
}
